import React from 'react';
import { Card, Form, Select, DatePicker, Button, Space, Table, Input, message } from 'antd';
import { BarChartOutlined } from '@ant-design/icons';
// 使用 ECharts 按需引入（推荐方式）
import echarts from '../../utils/echarts';
import dayjs from 'dayjs';

// 模仿 admin-web/src/views/statistics/AdverStatistics.vue
// 功能：搜索类型切换（金额/次数）、日期范围选择（月/日）、图表展示、表格与导出

const { RangePicker } = DatePicker;

const mockAds = (() => {
  const days = Array.from({ length: 14 }).map((_, i) => dayjs().subtract(13 - i, 'day').format('YYYY-MM-DD'));
  const price = days.map(() => parseFloat((50 + Math.random() * 300).toFixed(2)));
  const num = days.map(() => Math.floor(10 + Math.random() * 50));
  return { days, price, num };
})();

const initialTable = mockAds.days.map((d, idx) => ({
  key: idx,
  username: ['alice', 'bob', 'carol'][idx % 3],
  equipmentNo: `EQ-${1000 + idx}`,
  equipmentName: `设备-${idx + 1}`,
  head: `广告标题-${idx + 1}`,
  advertiser: ['Google', 'Meta', 'Amazon'][idx % 3],
  record: mockAds.num[idx],
  date: d,
}));

export default function AdverStatistics() {
  const [form] = Form.useForm();
  const chartRef = React.useRef(null);
  const chartInstance = React.useRef(null);
  const [tableData, setTableData] = React.useState(initialTable);
  const [searchType, setSearchType] = React.useState('price');
  const [cards, setCards] = React.useState({ today: 0, week: 0, month: 0, total: 0 });

  const handleResize = React.useCallback(() => {
    if (chartInstance.current) {
      chartInstance.current.resize();
    }
  }, []);

  const updateCards = React.useCallback((data, type = 'price') => {
    const todayStr = dayjs().format('YYYY-MM-DD');
    const todayList = data.filter((d) => d.date === todayStr);
    const sumBy = (arr) => arr.reduce((sum, cur) => sum + (type === 'price' ? cur.record * 3.5 : cur.record), 0);
    const today = sumBy(todayList);
    const week = sumBy(data.slice(-7));
    const month = sumBy(data);
    const total = sumBy(initialTable);
    setCards({ today, week, month, total });
  }, []);

  const renderChart = React.useCallback((data, type = 'price') => {
    const el = chartRef.current;
    if (!el) return;
    if (!chartInstance.current) {
      chartInstance.current = echarts.init(el);
    }
    const xData = data.map((d) => d.date);
    const yData = data.map((d) => (type === 'price' ? parseFloat((d.record * 3.5).toFixed(2)) : d.record));
    chartInstance.current.setOption({
      tooltip: { trigger: 'axis' },
      grid: { left: 40, right: 40, top: 30, bottom: 40 },
      xAxis: { type: 'category', data: xData },
      yAxis: { type: 'value' },
      series: [
        {
          type: type === 'price' ? 'line' : 'bar',
          data: yData,
          smooth: true,
          areaStyle: type === 'price' ? {} : undefined,
          itemStyle: { color: '#52c41a' },
        },
      ],
    }, true); // 使用 notMerge=true 以确保每次重绘
    chartInstance.current.resize();
  }, []);

  React.useEffect(() => {
    updateCards(tableData, searchType);
    renderChart(tableData, searchType);
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
      chartInstance.current && chartInstance.current.dispose();
    };
  }, []); // eslint-disable-line

  const columns = [
    { title: '用户', dataIndex: 'username', key: 'username' },
    { title: '设备编号', dataIndex: 'equipmentNo', key: 'equipmentNo' },
    { title: '设备名称', dataIndex: 'equipmentName', key: 'equipmentName' },
    { title: '标题', dataIndex: 'head', key: 'head' },
    { title: '广告主', dataIndex: 'advertiser', key: 'advertiser' },
    { title: '记录次数', dataIndex: 'record', key: 'record', align: 'right' },
    { title: '日期', dataIndex: 'date', key: 'date' },
  ];

  const onSearch = () => {
    const { dayType, dateRange, username, equipmentNo, head, advertiser } = form.getFieldsValue();
    let filtered = initialTable;
    if (dateRange && dateRange.length === 2) {
      const start = dayjs(dateRange[0]);
      const end = dayjs(dateRange[1]);
      filtered = filtered.filter((d) => {
        const cur = dayjs(d.date, 'YYYY-MM-DD');
        return cur.isAfter(start.subtract(1, 'day')) && cur.isBefore(end.add(1, 'day'));
      });
    }
    const includes = (val, q) => !q || String(val).toLowerCase().includes(String(q).toLowerCase());
    filtered = filtered.filter(
      (d) =>
        includes(d.username, username) &&
        includes(d.equipmentNo, equipmentNo) &&
        includes(d.head, head) &&
        includes(d.advertiser, advertiser)
    );
    setTableData(filtered);
    updateCards(filtered, searchType);
    renderChart(filtered, searchType);
  };

  const onReset = () => {
    form.resetFields();
    setTableData(initialTable);
    updateCards(initialTable, searchType);
    renderChart(initialTable, searchType);
  };

  const exportCSV = () => {
    const header = ['用户', '设备编号', '设备名称', '标题', '广告主', '记录次数', '日期'];
    const rows = tableData.map((r) => [r.username, r.equipmentNo, r.equipmentName, r.head, r.advertiser, r.record, r.date]);
    const csv = [header, ...rows].map((row) => row.join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `adver-statistics-${dayjs().format('YYYYMMDDHHmmss')}.csv`;
    a.click();
    URL.revokeObjectURL(url);
    message.success('导出成功');
  };

  return (
    <div>
      <div style={{ width: 1670, padding: 15, display: 'flex', alignItems: 'center' }}>
        <Card style={{ marginRight: 7.5 }}>
          <div style={{ display: 'flow-root', width: 380 }}>
            <div style={{ width: '100%' }}>{searchType === 'price' ? '今日广告播放金额' : '今日广告播放次数'}</div>
            <div style={{ fontSize: 28, textAlign: 'center', color: '#52c41a', fontWeight: 'bold', marginTop: 10 }}>
              {searchType === 'price' ? `$${cards.today.toFixed(2)}` : cards.today}
            </div>
          </div>
        </Card>
        <Card style={{ margin: '0 7.5px' }}>
          <div style={{ display: 'flow-root', width: 380 }}>
            <div style={{ width: '100%' }}>{searchType === 'price' ? '本周广告播放金额' : '本周广告播放次数'}</div>
            <div style={{ fontSize: 28, textAlign: 'center', color: '#52c41a', fontWeight: 'bold', marginTop: 10 }}>
              {searchType === 'price' ? `$${cards.week.toFixed(2)}` : cards.week}
            </div>
          </div>
        </Card>
        <Card style={{ margin: '0 7.5px' }}>
          <div style={{ display: 'flow-root', width: 380 }}>
            <div style={{ width: '100%' }}>{searchType === 'price' ? '本月广告播放金额' : '本月广告播放次数'}</div>
            <div style={{ fontSize: 28, textAlign: 'center', color: '#52c41a', fontWeight: 'bold', marginTop: 10 }}>
              {searchType === 'price' ? `$${cards.month.toFixed(2)}` : cards.month}
            </div>
          </div>
        </Card>
        <Card style={{ marginLeft: 7.5 }}>
          <div style={{ display: 'flow-root', width: 380 }}>
            <div style={{ width: '100%' }}>{searchType === 'price' ? '总广告播放金额' : '总广告播放次数'}</div>
            <div style={{ fontSize: 28, textAlign: 'center', color: '#52c41a', fontWeight: 'bold', marginTop: 10 }}>
              {searchType === 'price' ? `$${cards.total.toFixed(2)}` : cards.total}
            </div>
          </div>
        </Card>
      </div>

      <div
        style={{
          width: 1638,
          margin: '0 15px 15px 15px',
          padding: 15,
          backgroundColor: '#f3f3f3',
          display: 'flow-root',
          border: '1px solid #e7e7e7',
          borderRadius: 3,
        }}
      >
        <div style={{ float: 'left', lineHeight: '32px', width: 463, height: 30, fontSize: 15, display: 'flex', alignItems: 'center', gap: 8 }}>
          <BarChartOutlined style={{ color: '#52c41a', fontSize: 18 }} />
          <span>广告统计</span>
        </div>
        <div style={{ float: 'right' }}>
          <Select value={searchType} size="small" style={{ width: 160 }} onChange={(v) => { setSearchType(v); updateCards(tableData, v); renderChart(tableData, v); }}>
            <Select.Option value="price">广告金额</Select.Option>
            <Select.Option value="num">广告次数</Select.Option>
          </Select>
        </div>
      </div>

      <div style={{ width: 1670, padding: 15 }}>
        <div id="adverChart" ref={chartRef} style={{ width: 1670, height: 400 }} />
      </div>

      <div
        style={{
          width: 1638,
          margin: '0 15px 15px 15px',
          padding: 15,
          backgroundColor: '#f3f3f3',
          display: 'flow-root',
          border: '1px solid #e7e7e7',
          borderRadius: 3,
        }}
      >
        <div style={{ float: 'left', lineHeight: '32px', height: 30, fontSize: 15 }}>
          <Button type="primary" onClick={exportCSV} size="small" style={{ marginRight: 15 }}>
            导出
          </Button>
        </div>
        <div className="el-right">
          <Form form={form} layout="inline" initialValues={{ dayType: '2' }}>
            <Form.Item label="统计周期" name="dayType">
              <Select size="small" style={{ width: 170 }}>
                <Select.Option value="2">按月</Select.Option>
                <Select.Option value="3">按日</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item label="日期范围" name="dateRange">
              <RangePicker
                size="small"
                allowClear
                style={{ width: 335 }}
                picker={(form.getFieldValue('dayType') || '2') === '2' ? 'month' : 'date'}
                format={(form.getFieldValue('dayType') || '2') === '2' ? 'YYYY-MM' : 'YYYY-MM-DD'}
              />
            </Form.Item>
            <Form.Item label="用户" name="username">
              <Input size="small" allowClear style={{ width: 200 }} />
            </Form.Item>
            <Form.Item label="设备编号" name="equipmentNo">
              <Input size="small" allowClear style={{ width: 200 }} />
            </Form.Item>
            <Form.Item label="标题" name="head">
              <Input size="small" allowClear style={{ width: 200 }} />
            </Form.Item>
            <Form.Item label="广告主" name="advertiser">
              <Input size="small" allowClear style={{ width: 200 }} />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" size="small" onClick={onSearch}>
                  搜索
                </Button>
                <Button size="small" onClick={onReset}>重置</Button>
              </Space>
            </Form.Item>
          </Form>
        </div>
      </div>

      <div className="vue-padding radius">
        <Table
          dataSource={tableData}
          columns={columns}
          pagination={{ pageSize: 10 }}
          summary={(pageData) => {
            const totalRecord = pageData.reduce((sum, cur) => sum + cur.record, 0);
            return (
              <Table.Summary.Row>
                <Table.Summary.Cell index={0}>合计</Table.Summary.Cell>
                <Table.Summary.Cell index={1} />
                <Table.Summary.Cell index={2} />
                <Table.Summary.Cell index={3} />
                <Table.Summary.Cell index={4} />
                <Table.Summary.Cell index={5} align="right">{totalRecord.toLocaleString()}</Table.Summary.Cell>
                <Table.Summary.Cell index={6} />
              </Table.Summary.Row>
            );
          }}
        />
      </div>
    </div>
  );
}